package com.swdegao.iot.netty.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import io.netty.channel.Channel;

import com.swdegao.iot.netty.entity.CallBackData;
import com.swdegao.iot.netty.entity.ImeiInfo;
import com.swdegao.iot.netty.entity.MyProps;
import com.swdegao.iot.netty.entity.Parameter;
import com.swdegao.iot.netty.entity.PushMessage;
import com.swdegao.iot.netty.entity.UpData;
import com.swdegao.iot.netty.utils.Const;
import com.swdegao.iot.netty.utils.HttpClientUtil;
import com.swdegao.iot.netty.utils.RedisUtils;
import com.swdegao.iot.netty.service.CMDService;
import com.swdegao.iot.netty.service.CallBackService;

@Service
public class CallBackServiceImpl implements CallBackService {

	//定义一个全局的记录器，通过LoggerFactory获取
    private final static Logger logger = LoggerFactory.getLogger(CallBackServiceImpl.class); 
	
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
    private MyProps myProps;

	@Override
	public void doSendHttpPost(CallBackData callBackData){
		try {
			String url = callBackData.getUrl();
			if(  "".equals(url))url = myProps.getMycallbackurl();
		    Pattern p = Pattern.compile(Parameter.regUrl);
		    Matcher m = p.matcher(url);
			if (!m.matches()) {
				logger.info("Url地址错误");
			}
			long nowtime = System.currentTimeMillis();
			String imei = callBackData.getImei();
			PushMessage pusmessage = new PushMessage();
			pusmessage.setImei(imei);
			pusmessage.setServiceId("");
			pusmessage.setPushTime(nowtime);

			// 从msg中获取updata
			List<UpData> list = new ArrayList<UpData>();
			UpData updata = new UpData();
			updata.setCreatetime(callBackData.getCreatetime());
			updata.setImei(imei);

			// logger.info(imei+"###########################" +
			// Hex.encodeHexString(receiveMsgBytes));
			updata.setUpData(callBackData.getUpData());
			list.add(updata);
			pusmessage.setUpDataList(list);
			// logger.error(imei+"Parametercall_back_url"+url);
			try {
				HttpClientUtil.sendHttpPostJson(url, JSON.toJSONString(pusmessage));
			} catch (Exception e) {
				logger.info("CallBackServiceImpl-doSendHttpPostC 推送异常："+e.getMessage());
			}

		}catch(Exception e) {
			logger.info("CallBackServiceImpl-doSendHttpPostC 推送异常："+e.getMessage());
		}
		

	}
}
